import axios from "axios";
import { GetAsyncOptions, PostAsyncOptions, baseURL } from './constent'
import router from '../router/index'

const instance = axios.create({
  timeout: 10000,
  headers: { 'Content-Type': "application/json" },
  baseURL
})

// 请求拦截回调
const requestInterceptors = (config) => {
  // 在 localStorage 获取 token
  let token = localStorage.getItem("token");

  // 如果存在则设置请求头
  if (token) {
    config.headers.Authorization = token;
  }

  // 在发送请求之前做些什么
  return config
}

const requestInterceptorsError = (error) => {
  // 对请求错误做些什么
  return Promise.reject(error)
}

// 响应拦截回调
const responseInterceptors = (response) => {
  return response.data.errorCode !== 0 ? Promise.reject(response) : response
}

const responseInterceptorsError = (error) => {
  if (error.response.status == '401') {
    router.push('/login')
  }
  return Promise.reject("Not Allowed");
}


// 添加请求拦截器
instance.interceptors.request.use(requestInterceptors, requestInterceptorsError);

// 添加响应拦截器
instance.interceptors.response.use(responseInterceptors, responseInterceptorsError)

const service = {
  /**
   * 封装 post 方法
   * @param url
   * @param data
   * @param headers
   */
  async postAsync({ url, data, headers }: PostAsyncOptions): Promise<any> {
    try {
      let res = await instance.post(url, data, { headers: headers })
      return res.data
    } catch (error) {
      throw {
        error,
        message: 'post请求出错'
      }
    }
  },
  /**
   * 封装 get 方法
   * @param url
   * @param params
   * @param headers
   */
  async getAsync({ url, params, headers }: GetAsyncOptions): Promise<any> {
    try {
      let res = await instance.get(url, {
        params: params,
        headers: headers
      })
      return res.data
    } catch (error) {
      throw {
        error,
        message: 'get请求出错'
      }
    }
  },
}

export default service
